<?php

class AdminPlacesController extends AdminController
{
    /**
     * Place Model
     * @var Place
     */
    protected $place;

    protected $branch;
    /**
     * Inject the models.
     * @param Post $post
     */
    public function __construct(Place $place, ProvincePlaces $branch)
    {
        parent::__construct();
        $this->place = $place;
        $this->branch = $branch;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function getIndex()
    {
        // Grab all the groups
        $places = $this->place->paginate(10);
        $provinces = Province::all();
        $branchs = $this->branch->paginate(20);

        // Show the page
        return View::make('admin/places/index', compact('places', 'provinces', 'branchs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function getCreate()
    {
        $categories = Category::all();
        $provinces = Province::all();
        // Show the page
        return View::make('admin/places/create', compact('categories', 'provinces'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function postCreate()
    {
        // Declare the rules for the form validation
        $rules = array(
            'name'   => 'required|min:3',
            'logo' => 'mimes:jpeg,bmp,png,gif|max:3000',
            'email' => 'email',
            'website' => 'url'
        );

        // Validate the inputs
        $validator = Validator::make(Input::all(), $rules);

        // Check if the form validates with success
        if ($validator->passes()) {
            $file = Input::file('logo');
            if ($file) {

                $originalName = $file->getClientOriginalName();
                $filename = Str::random(36) .'.'. File::extension($originalName);
                if ($file->move(base_path().'/public/uploads/images/', $filename)) {
                    $this->place->logo =  $filename;
                    Image::make(base_path().'/public/uploads/images/'. $filename)
                    ->resize(null, 120, true)
                    ->save(base_path().'/public/uploads/images/thumb/'. $filename);
                }
            }

            $this->place->name = Input::get('name');
            $this->place->description = Input::get('description');
            $this->place->category_id = Input::get('category');

            //TODO: for tmp
            $this->place->logo = Input::get('logo');

            if ($this->place->save()) {
                $this->saveNewBranch(Input::get('provinces'), $this->place);
                // Redirect to the new blog post page
                return Redirect::to('admin/places/' . $this->place->id . '/edit')->with('success', Lang::get('admin/places/messages.create.success'));
            }
             // Redirect to the place create page
            return Redirect::to('admin/places/create')->with('error', Lang::get('admin/places/messages.create.error'));

        }
        // Form validation failed
        return Redirect::to('admin/places/create')->withInput()->withErrors($validator);

    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param $place
     * @return Response
     */
    public function getEdit($place)
    {
        //echo 'Hello';
        // Show the page
        $categories = Category::all();
        $provinces = Province::all();
        $oldProvincesObject = ProvincePlaces::where('place_id', $place->id)->get();
        $oldProvinces = array();
        foreach ($oldProvincesObject as $op) {
            $oldProvinces[] = $op->province_id;
        }

        return View::make('admin/places/edit', compact('place', 'categories', 'provinces', 'oldProvinces'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  $place
     * @return Response
     */
    public function postEdit($place)
    {
        // Declare the rules for the form validation
        $rules = array(
            'name'   => 'required|min:3',
            'logo' => 'mimes:jpeg,bmp,png,gif|max:3000',
            'email' => 'email',
            'website' => 'url'
        );

        // Validate the inputs
        $validator = Validator::make(Input::all(), $rules);

        // Check if the form validates with success
        if ($validator->passes()) {

            $file = Input::file('logo');
            if ($file) {

                $originalName = $file->getClientOriginalName();
                $filename = Str::random(36) .'.'. File::extension($originalName);

                if ($file->move(base_path().'/public/uploads/images/', $filename)) {

                    // Delete old file
                    File::delete(base_path().'/public/uploads/images/' . $place->logo);
                    File::delete(base_path().'/public/uploads/images/thumb/' . $place->logo);

                    $place->logo = $filename;
                    Image::make(base_path().'/public/uploads/images/'. $filename)
                    ->resize(null, 120, true)
                    ->save(base_path().'/public/uploads/images/thumb/'. $filename);
                }
            }

            $place->name = Input::get('name');
            $place->description = Input::get('description');
            $place->category_id = Input::get('category');
            $oldProvinces = json_decode( Input::get('oldprovince'));

            //TODO: for tmp
            $place->logo = Input::get('logo');

            if ($place->save()) {
                $this->savePronvincePlace(Input::get('provinces'), $place, $oldProvinces);
                // Redirect to the new blog post page
                return Redirect::to('admin/places/' . $place->id . '/edit')->with('success', Lang::get('admin/places/messages.update.success'));
            }
             // Redirect to the place create page
            return Redirect::to('admin/places/' . $place->id . '/edit')->with('error', Lang::get('admin/places/messages.update.error'));

        }
        // Form validation failed
        return Redirect::to('admin/places/' . $place->id . '/edit')->withInput()->withErrors($validator);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param $place
     * @return Response
     */
    public function getDelete($place)
    {
        // Show the page
        return View::make('admin/places/delete', compact('place'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param $place
     * @return Response
     */
    public function postDelete($place)
    {
        // Declare the rules for the form validation
        $rules = array(
            'id' => 'required|integer'
        );

        // Validate the inputs
        $validator = Validator::make(Input::all(), $rules);

        // Check if the form validates with success
        if ($validator->passes()) {
            $id = $place->id;
            $place->delete();
            // Delete all Branches
            ProvincePlaces::where('place_id', $id)->delete();

            // Was the place deleted?
            $place = Place::find($id);
            if (empty($place)) {
                // Redirect to the blog posts management page
                return Redirect::to('admin/places')->with('success', Lang::get('admin/places/messages.delete.success'));
            }

        }
        // There was a problem deleting the blog post
        return Redirect::to('admin/places')->with('error', Lang::get('admin/places/messages.delete.error'));
    }

    private function savePronvincePlace($provinces, $place, $oldProvinces = false)
    {

        foreach ($provinces as $pid) {

            if ( is_array($oldProvinces) && in_array($pid, $oldProvinces) ) {
                if (($key = array_search($pid, $oldProvinces)) !== false) {
                        unset($oldProvinces[$key]);
                }
            } else {
                $pronvincePlace = new ProvincePlaces();
                $pronvincePlace->province_id = $pid;
                $pronvincePlace->place_id = $place->id;
                $pronvincePlace->save();
            }
        }

        if (count($oldProvinces) > 0) {
            ProvincePlaces::where('place_id', $place->id)
                            ->whereIn('province_id', $oldProvinces)
                            ->delete();
        }
    }
    private function saveNewBranch($provinces, $place)
    {
        foreach ($provinces as $pid) {

            $pronvincePlace = new ProvincePlaces();
            $pronvincePlace->province_id = $pid;
            $pronvincePlace->place_id = $place->id;
            $pronvincePlace->save();

        }
    }
}
